<template>
  <a-page-header>
    <a-row>
      <a-col :span="4">
        <a-card>
          <a-input-search style="margin-bottom: 8px" placeholder="Search" />
          <a-tree
              ref="leftTree"
              show-line
              :autoExpandParent="leftTree.autoExpandParent"
              :expandedKeys="leftTree.expandedKeys"
              @select="onLeftTreeSelect"
              @expand="onExpand"
              :tree-data="leftTree.data"
              :replaceFields="leftTree.selectLeftTreeReplaceFields"
          >
          </a-tree>
        </a-card>
      </a-col>
      <a-col :span="20">
        <a-card>
          <a-table :columns="columns" :data-source="data"
                   :loading="loading"
                   :rowKey="record => record.cinemaId" >
            <template slot="title">
              <a-row type="flex" justify="space-between">
                <a-col :span="4">
                  <a-button type="primary" style="margin-left: 10px;" icon="plus-circle" @click="showAddModal()" >
                    新增影院
                  </a-button>
                  <a-modal
                      :title="modalForm.title"
                      :visible="modalForm.visible"
                      :confirm-loading="modalForm.confirmLoading"
                      okText="提交"
                      cancelText="取消"
                      @ok="handleModalOk"
                      @cancel="handleModalCancel">
                    <a-form-model @submit="handleModalFormSubmit"
                                  :label-col="{span:4}" :wrapper-col="{span:14}" ref="addForm"
                                  :model="addForm" :rules="modalForm.modalFormRules"  >
                      <a-form-model-item label="所属地域" ref="areaId" prop="areaId">
                        <a-tree-select
                            v-model="addForm.areaId"
                            style="width: 100%"
                            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                            :tree-data="leftTree.data"
                            placeholder="请选择所属地域"
                            :replaceFields="leftTree.selectLeftTreeReplaceFields"
                        >
                        </a-tree-select>
                      </a-form-model-item>

                      <a-form-model-item label="影院名称" ref="cinemaName" prop="cinemaName">
                        <a-input v-model="addForm.cinemaName" placeholder="影院名称"/>
                      </a-form-model-item>

                      <a-form-model-item label="影院地址" ref="cinemaAddress" prop="cinemaAddress">
                        <a-input v-model="addForm.cinemaAddress"  placeholder="影院地址" />
                      </a-form-model-item>

                      <a-form-model-item label="影院电话" ref="cinemaTel" prop="cinemaTel">
                        <a-input v-model="addForm.cinemaTel"  placeholder="影院电话" />
                      </a-form-model-item>

                      <a-form-model-item label="影院信息" ref="cinemaInfo" prop="cinemaInfo">
                        <a-input v-model="addForm.cinemaInfo"  placeholder="影院信息" />
                      </a-form-model-item>

                      <a-form-model-item label="影院交通" ref="cinemaTransport" prop="cinemaTransport">
                        <a-input v-model="addForm.cinemaTransport"  placeholder="影院交通" />
                      </a-form-model-item>

                      <a-form-model-item label="是否启用" ref="status" prop="status">
                        <a-radio-group v-model="addForm.status">
                          <a-radio-button :value="1">
                            启用
                          </a-radio-button>
                          <a-radio-button :value="0">
                            禁用
                          </a-radio-button>
                        </a-radio-group>
                      </a-form-model-item>
                    </a-form-model>

                  </a-modal>
                </a-col>

                <a-col >
                  <a-form-model ref="queryForm"
                                layout="inline" :model="formInline">
                    <a-form-model-item ref="cinemaNameLike" prop="cinemaNameLike">
                      <a-input v-model="formInline.cinemaNameLike" placeholder="模糊查询影院名称">
                      </a-input>
                    </a-form-model-item>

                    <a-form-model-item ref="searchStatus" prop="searchStatus">
                      <a-select v-model="formInline.searchStatus" style="width: 200px" placeholder="请选择要查询的影院状态">
                        <a-select-option value="1">
                          启用
                        </a-select-option>
                        <a-select-option value="0">
                          禁用
                        </a-select-option>
                        <a-select-option value="3">
                          逻辑删除
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>

                    <a-form-model-item>
                      <a-button
                          type="primary"
                          @click="handleSubmit"
                          :disabled="isDisable">
                        查询
                      </a-button>
                      <a-button style="margin-left: 10px;" @click="resetSearchForm('queryForm')">
                        重置
                      </a-button>
                    </a-form-model-item>
                  </a-form-model>
                </a-col>
              </a-row>
            </template>

            <template #areaId="areaId">
              {{getAreaName(areaId)}}
            </template>

            <template #status="status">
              <a-tag v-if="status===1" :color="'green'">
                <span>启用</span>
              </a-tag>
              <a-tag v-else-if="status===0" :color="'volcano'">
                <span>禁用</span>
              </a-tag>
              <a-tag v-else-if="status===3" :color="'red'">
                <span>逻辑删除</span>
              </a-tag>
              <a-tag v-else :color="'purple'">
                <span>{{'未适配:'+status}}</span>
              </a-tag>
            </template>

            <template #action="record">
              <a-button type="primary" shape="circle" icon="edit" @click="showEditModal(record)" />
              <a-divider type="vertical" />
              <a-popconfirm
                  :title="`确认要删除:${record.cinemaName}吗?`"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="handleDeleteCinema(record.cinemaId)"
              >
                <a-icon slot="icon" type="question-circle-o" style="color: red" />
                <a-button type="danger" shape="circle" icon="delete" />
              </a-popconfirm>

            </template>

          </a-table>
        </a-card>
      </a-col>
    </a-row>



  </a-page-header>
</template>

<script>
import {getAreaTree} from "@/api/area";
import {addCinema,updateCinema,getCinemaListCondition,logicDeleteCinemaById} from "@/api/cinema"
const columns = [
  {
    title: '影院标识',
    dataIndex: 'cinemaId',
    key: 'cinemaId',
  },
  {
    title: '影院名称',
    dataIndex: 'cinemaName',
    key: 'cinemaName',
  },
  {
    title: '影院地址',
    dataIndex: 'cinemaAddress',
    key: 'cinemaAddress',
  },
  {
    title: '影院电话',
    dataIndex: 'cinemaTel',
    key: 'cinemaTel',
  },
  {
    title: '影院信息',
    dataIndex: 'cinemaInfo',
    key: 'cinemaInfo',
  },
  {
    title: '影院交通',
    dataIndex: 'cinemaTransport',
    key: 'cinemaTransport',
  },
  {
    title: '影院图片路径',
    dataIndex: 'cinemaPic',
    key: 'cinemaPic',
    ellipsis: true,
  },
  {
    title: '所属地域',
    dataIndex: 'areaId',
    key: 'areaId',
    scopedSlots: { customRender: 'areaId' },
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  }
];

const selectLeftTreeReplaceFields = {
  children:'children',
  title:'areaName',
  key:'areaId',
  value: 'areaId'
}

const modalFormRules = {
  areaId: [
    {required: true, message: '请选择所属地域',trigger:['blur','change']},
  ],
  cinemaName: [
    {required: true, message: '请输入影院名称', trigger: ['blur']},
  ],
  cinemaAddress: [
    {required: true, message: '请输入影院地址', trigger: ['blur']},
  ],
  cinemaInfo: [
    {required: false, message: '请输入影院信息', trigger: ['blur']},
  ],
  cinemaTel: [
    {required: false, message: '请输入影院电话', trigger: ['blur']},
  ],
  cinemaTransport: [
    {required: false, message: '请输入去影院的交通方式', trigger: ['blur']},
  ],
  status:[
    {required: true, message: '请选择是否启用', trigger: 'change'}
  ]
}
export default {
  name: "SystemCinema",
  data() {
    return {
      leftTree:{
        expandedKeys: [1],
        searchValue: '',
        autoExpandParent: true,
        selectLeftTreeReplaceFields,
        data:[],
        selectedKeys:[1],
      },
      formInline: {
        cinemaNameLike: '',
        searchStatus: undefined,
      },
      modalForm:{
        title:'',
        visible:false,
        confirmLoading: false,
        modalFormRules,
        isDisabled:false
      },
      addForm:{
        cinemaId:undefined,
        cinemaPic:'',
        cinemaAddress:'',
        cinemaTel:'',
        cinemaInfo:'',
        cinemaTransport:'',
        areaId:undefined,
        cinemaName:'',
        status:undefined,
      },
      data:[],
      loading:false,
      columns,
      isHandleSubmit:false,
    }
  },
  mounted() {
    this.getCinemaListData()
    this.getAreaTreeData()
  },
  methods:{
    //左侧树形
    onLeftTreeSelect(selectedKeys, info){
      console.log('selectedLeftTreeSelect', selectedKeys, info);
      this.leftTree.selectedKeys = selectedKeys;
      this.getCinemaListData({areaId:selectedKeys[0]})
    },
    onExpand(expandedKeys) {
      console.log(expandedKeys)
      this.leftTree.expandedKeys = expandedKeys;
      this.leftTree.autoExpandParent = false;
    },
    getAreaName(areaId){
      let c = [];
      c.push(this.leftTree.data)
      while (c.length!==0){
        let items = c.shift()
        for (let item of items){
          if (item.areaId===areaId){
            return item.areaName
          }
          if (item.children){
            c.push(item.children)
          }
        }
      }
      return areaId
    },
    // 查询表单提交
    print(a,b){
      console.log(a,b)
    },
    handleSubmit() {
      console.log(this.formInline)
      this.isHandleSubmit = true;
      let submitParams = {
        areaId:this.leftTree.selectedKeys[0]
      }
      if (this.formInline.cinemaNameLike!==''){
        submitParams['cinemaNameLike'] = this.formInline.cinemaNameLike
      }
      if (typeof (this.formInline.searchStatus)!=='undefined'){
        submitParams['cinemaStatus']=this.formInline.searchStatus
      }
      console.log('SystemApi handleSubmit',submitParams)
      this.getCinemaListData(submitParams)
    },
    resetSearchForm(formName) {
      this.$refs[formName].resetFields();
      if (this.isHandleSubmit){
        this.getCinemaListData()
      }
    },
    getCinemaListData(params={areaId:1}){
      this.loading = true
      getCinemaListCondition(params).then(res=>{
        this.data = res.data
      }).catch(err=>{
        console.log("SystemCinema:getCinemaListData:"+err.message);
      }).finally(()=>{
        this.loading = false
      })
    },

    // 获取树形API数据
    getAreaTreeData(param= {rootAreaId:1}){
      getAreaTree(param).then(res=>{
        this.leftTree.data = res.data
      }).catch(err=>{
        console.log("SystemCinema:getAreaTreeData:"+err.message);
      })
    },
    // addForm start
    showAddModal(){
      this.modalForm.isDisabled = false;
      this.modalForm.visible =  true
      this.modalForm.title = '新增影院'
    },
    showEditModal(record){
      console.log(record)
      this.modalForm.isDisabled = true
      this.modalForm.visible =  true
      this.modalForm.title = '修改影院'
      let {cinemaId, areaId, cinemaName,status,cinemaAddress,cinemaTel,cinemaInfo,cinemaTransport,cinemaPic} = record
      this.addForm = {
        cinemaId, areaId, cinemaName,cinemaAddress,cinemaTel,cinemaInfo,cinemaTransport,cinemaPic,status
      }
    },
    // 处理modal里的表单提交
    handleModalOk(){
      this.handleModalFormSubmit()
    },
    handleModalCancel(){
      this.modalForm.visible = false
      this.resetForm('addForm')
    },
    handleModalFormSubmit(){
      this.$refs['addForm'].validate(valid=>{
        if (valid) {
          let submitData = this.addForm
          // submitData.status = this.addForm.status === "1"
          this.modalForm.confirmLoading = true
          if (this.modalForm.isDisabled){
            this.handleUpdateCinema(submitData)
          }else {
            this.handleAddCinema(submitData)
          }
        } else {
          this.handleFiled(new Error('表单校验不通过'))
          return false;
        }
      })
    },
    resetForm(formName) {
      this.addForm = {
        cinemaId:undefined,
        cinemaPic:'',
        cinemaAddress:'',
        cinemaTel:'',
        cinemaInfo:'',
        cinemaTransport:'',
        areaId:undefined,
        cinemaName:'',
        status:undefined,
      }
      this.$refs[formName].resetFields();
    },
    // addForm end
    handleAddCinema(cinema){
      addCinema(cinema).then(res=>{
        this.handleSuccess(res)
        this.resetForm('addForm')
      }).catch(err=> this.handleFiled(err))
    },
    handleDeleteCinema(cinemaId){
      logicDeleteCinemaById(cinemaId).then(res=>{
        this.handleSuccess(res)
      }).catch(err=> this.handleFiled(err))
    },
    handleUpdateCinema(cinema){
      updateCinema(cinema).then(res=>{
        this.handleSuccess(res)
        this.resetForm('addForm')
      }).catch(err=> this.handleFiled(err))
    },
    handleSuccess(res){
      this.modalForm.confirmLoading = false
      this.$notification['success']({
        message: '成功',
        description: `${res.data}`,
        duration: 4
      })
      this.getCinemaListData()
    },
    handleFiled(err){
      this.modalForm.confirmLoading = false
      console.log(err.message)
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).message || {}).message||err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  },

  computed:{
    isDisable(){
      return this.formInline.cinemaNameLike===''&&!this.formInline.searchStatus;
    }
  }
}
</script>

<style scoped>

</style>
